Js常用方法

2019.2.5 星期三 16:35

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
/**
* Cookie
*/
function getCookie(name){
var reg=new RegExp("(^| )"+name+"=([^;]*)(;|$)")
var arr=document.cookie.match(reg)
return (arr?arr[2]:null)
}
// 设置存储数据
function setStorage(key, val, cookie, day){
var cookie = key + "=" + encodeURIComponent(val),
days = (typeof(day) == 'undefined' || day == 0) ? 3650 : day,// 过期时间,默认10年
exp = new Date();
exp.setTime(exp.getTime() + days * 24 * 60 * 60 * 1000);
cookie = cookie + ";domain=" + cookieDomain + ";path=/;expires=" + exp.toGMTString();
document.cookie = cookie;
}
// 删除存储数据
function delStorage(key, cookie){
if($.trim(key)){
var exp = new Date(),
cval = getStorage(key, 'cookie');
exp.setTime(exp.getTime() - 1);
if(cval != null){
document.cookie = key + "=" + cval + ";domain=" + cookieDomain + ";path=/;expires=" + exp.toGMTString();
}
}
}
// 清除存储数据
function clearStorage(cookie){
var key = document.cookie.match(/[^ =;]+(?=\=)/g);
if(key){
for(var i = key.length - 1; i >= 0; i--){
var exp = new Date(),
cval = getStorage(key[i], 'cookie');
exp.setTime(exp.getTime() - 1);
document.cookie = key[i] + "=" + cval + ";domain=" + cookieDomain + ";path=/;expires=" + exp.toGMTString();
}
}
}


/**
* 函数节流/去抖
*/
function debounce(fn, wait) {
var timer = null;
return function () {
var context = this
var args = arguments
if (timer) {
clearTimeout(timer);
timer = null;
}
timer = setTimeout(function () {
fn.apply(context, args)
}, wait)
}
}
function throttle(fn, wait) {
var previous = 0
var timer = null
return function () {
var context = this
var args = arguments
if (!previous) {
previous = Date.now()
fn.apply(context, args)
} else if (previous + wait >= Date.now()) {
if (timer) {
// console.log(timer)
clearTimeout(timer)
timer = null
}
// console.log(timer)
timer = setTimeout(function () {
// console.log(timer)
previous = Date.now()
fn.apply(context, args)
}, wait)
} else {
previous = Date.now()
fn.apply(context, args)
}
}
}
knowledge is no pay,reward is kindness
0%